/**
 * 登录状态管理工具 - 2506销售端
 * 处理token、用户信息、登录状态等
 */

import { authApi } from '@/request/api.js'

// 存储键名常量
const STORAGE_KEYS = {
  TOKEN: 'token',
  REFRESH_TOKEN: 'refreshToken',
  USER_INFO: 'userInfo',
  LOGIN_TIME: 'loginTime'
}

class AuthManager {
  constructor() {
    this.token = null
    this.refreshToken = null
    this.userInfo = null
    this.init()
  }

  // 初始化，从本地存储恢复登录状态
  init() {
    this.token = uni.getStorageSync(STORAGE_KEYS.TOKEN)
    this.refreshToken = uni.getStorageSync(STORAGE_KEYS.REFRESH_TOKEN)
    this.userInfo = uni.getStorageSync(STORAGE_KEYS.USER_INFO)
  }

  // 保存登录信息
  saveLoginInfo(loginResult) {
    const { token, refreshToken, userInfo } = loginResult

    if (token) {
      this.token = token
      uni.setStorageSync(STORAGE_KEYS.TOKEN, token)
    }

    if (refreshToken) {
      this.refreshToken = refreshToken
      uni.setStorageSync(STORAGE_KEYS.REFRESH_TOKEN, refreshToken)
    }

    if (loginResult) {
      this.userInfo = loginResult
      uni.setStorageSync(STORAGE_KEYS.USER_INFO, loginResult)
    }

    // 记录登录时间
    uni.setStorageSync(STORAGE_KEYS.LOGIN_TIME, Date.now())
  }

  // 获取token
  getToken() {
    return this.token || uni.getStorageSync(STORAGE_KEYS.TOKEN)
  }

  // 获取用户信息
  getUserInfo() {
    return this.userInfo || uni.getStorageSync(STORAGE_KEYS.USER_INFO)
  }

  // 检查是否已登录
  isLoggedIn() {
    return !!this.getToken()
  }

  // 清除登录信息
  clearLoginInfo() {
    this.token = null
    this.refreshToken = null
    this.userInfo = null

    uni.removeStorageSync(STORAGE_KEYS.TOKEN)
    uni.removeStorageSync(STORAGE_KEYS.REFRESH_TOKEN)
    uni.removeStorageSync(STORAGE_KEYS.USER_INFO)
    uni.removeStorageSync(STORAGE_KEYS.LOGIN_TIME)
  }

  // 刷新token
  async refreshAccessToken() {
    try {
      const refreshToken = this.refreshToken || uni.getStorageSync(STORAGE_KEYS.REFRESH_TOKEN)
      
      if (!refreshToken) {
        throw new Error('没有refresh token')
      }

      const result = await authApi.refreshToken({ refreshToken })
      
      // 保存新的token信息
      this.saveLoginInfo(result)
      
      return result.token
    } catch (error) {
      console.error('刷新token失败:', error)
      // 刷新失败，清除登录信息
      this.clearLoginInfo()
      throw error
    }
  }

  // 登出
  async logout() {
    try {
      // 调用登出接口
      await authApi.logout()
    } catch (error) {
      console.error('登出接口调用失败:', error)
    } finally {
      // 无论接口是否成功，都清除本地登录信息
      this.clearLoginInfo()
    }
  }

  // 检查token是否过期（简单检查，实际应该解析JWT）
  isTokenExpired() {
    const loginTime = uni.getStorageSync(STORAGE_KEYS.LOGIN_TIME)
    if (!loginTime) return true

    // 假设token有效期为7天
    const tokenValidDuration = 7 * 24 * 60 * 60 * 1000
    return Date.now() - loginTime > tokenValidDuration
  }

  // 获取完整的用户信息（从服务器）
  async fetchUserInfo() {
    try {
      const userInfo = await authApi.getUserInfo()
      this.userInfo = userInfo
      uni.setStorageSync(STORAGE_KEYS.USER_INFO, userInfo)
      return userInfo
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 检查登录状态并处理过期
  async checkLoginStatus() {
    if (!this.isLoggedIn()) {
      return false
    }

    // 如果token可能过期，尝试刷新
    if (this.isTokenExpired()) {
      try {
        await this.refreshAccessToken()
        return true
      } catch (error) {
        return false
      }
    }

    return true
  }

  // 需要登录时的处理
  requireLogin(options = {}) {
    const { 
      showModal = true, 
      title = '登录提示', 
      content = '请先登录后再进行操作',
      redirectUrl = '/pages/login/index'
    } = options

    if (showModal) {
      uni.showModal({
        title,
        content,
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: redirectUrl
            })
          }
        }
      })
    } else {
      uni.navigateTo({
        url: redirectUrl
      })
    }
  }
}

// 创建单例实例
const authManager = new AuthManager()

// 导出实例和常用方法
export default authManager

export const {
  saveLoginInfo,
  getToken,
  getUserInfo,
  isLoggedIn,
  clearLoginInfo,
  logout,
  checkLoginStatus,
  requireLogin,
  fetchUserInfo
} = authManager 